-- #############################################################################
-- mpi-tests2.lua
-- 
-- by Jacob Smith <http://code.google.com/p/lua-mpi/>
-- Copyright (C) 2009 Jacob Smith, All Rights Reserved
-- 
-- MPI extra tests.
-- 
-- $Id: mpi-tests2.lua 16 2009-08-06 04:15:21Z kloptops $

-- #############################################################################
-- Import stuff we require.
require('mpi');

function mpi_isprime(a)
    local match, which = mpi_divis_primes(a);
    if match ~= false then
        return false;
    end

    if mpi_fermat(a, 2) ~= true  then
        return false;
    end

    if mpi_pprime(a, 15) ~= true then
        return false;
    end

    return true;
end

math.randomseed(os.time() + os.clock())
a = mpi_new();
b = mpi_new();
mpi_random_bits(a, 128);
mpi_random_bits(b, 128);
print(mpi_bitcount(a), mpi_bitcount(b));

if mpi_iseven(a) then mpi_add_d(a, 1); end
if mpi_iseven(b) then mpi_add_d(b, 1); end

print(mpi_tostring(a, 16));
print(mpi_tostring(b, 16));


co_isprime1 = mpi_coroutine_wrap(mpi_isprime, "prime1")
co_isprime2 = mpi_coroutine_wrap(mpi_isprime, "prime2")

pass1, result1 = co_isprime1(1000, a)
pass2, result2 = co_isprime2(1000, b)
while pass1 and pass2 do
    print("-- 1 and 2")
    pass1, result1 = co_isprime1();
    pass2, result2 = co_isprime2();
end
while pass1 do
    print("-- 1")
    pass1, result1 = co_isprime1();
end
while pass2 do
    print("-- 2")
    pass2, result2 = co_isprime2();
end
print(result1, result2);

-- 
-- while mpi_isprime(a) ~= true do
--     print("Not Prime: " .. mpi_tostring(a, 16))
--     mpi_add_d(a, 2);
-- end
-- 
-- print("Prime: " .. mpi_tostring(a, 16))
-- 
-- while mpi_isprime(b) ~= true do
--     print("Not Prime: " .. mpi_tostring(b, 16))
--     mpi_add_d(b, 2);
-- end
-- print("Prime: " .. mpi_tostring(b, 16))
